import {sendGet, sendPost} from "./request";
import { getToken, setToken } from "./auth"

/**
 * 解析链接参数
 * @returns {{}}
 */
export function parseUrlParams() {
    let params_temp = window.document.location.search.substr(1).split('&')
    let params_temp2 = []
    let params = {}
    params_temp.forEach((item) => {
        params_temp2 = item.split('=')
        if(params_temp2.length === 2) {
            params[params_temp2[0]] = params_temp2[1]
        }
    })
    return params
}

export function entry() {
    return new Promise((resolve, error) => {
        const token = getToken()
        let params = parseUrlParams()
        if(!token) {
            if(params.code) {
                sendPost('login', {
                    code: params.code
                })
                    .then((res) => {
                        setToken(res.data.access_token)
                        resolve()
                    })
                    .catch((errors) => {
                        error(errors)
                    })
            } else {
                // 请求公众号登录授权数据
                sendGet('getOauthData')
                    .then((res) => {
                        let { wechat_appid, redirect_url } = res.data.data
                        redirect_url += window.document.location.search;
                        redirect_url = encodeURIComponent(redirect_url)
                        //console.log(wechat_appid, redirect_url)
                        window.location.href = '//open.weixin.qq.com/connect/oauth2/authorize?appid='+ wechat_appid +'&redirect_uri='+ redirect_url +'&response_type=code&scope=snsapi_userinfo&state='+ new Date().getTime() +'#wechat_redirect'
                    })
                    .catch((errors) => {
                        error(errors)
                    })
            }
        } else {
            resolve()
        }
    })
}

export default entry
